package com.example.day13_7_13_2;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView lv_list;
    private MySqllite mySqllite;
    private List<Student> list;
    private InfoAdapter infoAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySqllite = new MySqllite(this, "my.db", null, 1);
        SQLiteDatabase writableDatabase = mySqllite.getWritableDatabase();
        writableDatabase.execSQL("delete from student");
        initData();
        initView();
        setData();
    }

    private void setData() {
        List<Student> list = mySqllite.queryAll();
        Log.i(TAG, "setData: " + list.size());
        this.list.clear();
        this.list.addAll(list);
        infoAdapter.notifyDataSetChanged();
    }

    private void initData() {
        mySqllite.insert(new Student(1,"张三",19));
        mySqllite.insert(new Student(2,"张三2",19));
        mySqllite.insert(new Student(3,"张三3",19));
        mySqllite.insert(new Student(4,"张三4",19));
        mySqllite.insert(new Student(5,"张三5",19));
        mySqllite.insert(new Student(6,"张三6",19));
        mySqllite.insert(new Student(7,"张三7",19));
        mySqllite.insert(new Student(8,"张三8",19));
        mySqllite.insert(new Student(9,"张三9",19));
        mySqllite.insert(new Student(10,"张三10",19));
        mySqllite.insert(new Student(11,"张三11",19));
    }

    private static final String TAG = "MainActivity";

    private void initView() {
        lv_list = findViewById(R.id.lv_list);
        list = new ArrayList<>();
        infoAdapter = new InfoAdapter(this, list);
        lv_list.setAdapter(infoAdapter);
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("是否删除")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mySqllite.delete(list.get(position));
                                setData();
                            }
                        }).show();
            }
        });
    }
}
